import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Vibration } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar } from 'react-native-elements';
import { primaryColor, executor, toast } from './utils';
import { StoragePageQuery } from './graphql';

const styles = StyleSheet.create({
  button: {
    marginTop: 16
  }
});

class StoreCheckInPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `Check In to '${navigation.state.params.title}'`,
    };
  }
  state = { items: [] }
  onChangeText = (content) => {
      this.setState({content});
  }
  onSearch=()=>{
    content = parseInt(this.state.content);
    if (!content||isNaN(content)||(content.length>5)) {
      this.setState({content:null});
    } else {
      content = `${parseInt(content)}`;
      if (content.length>=5) {
        executor(this.props.loadOrder, content)
          .then(({res}) => {
            if (res) {
              this.setState({items: [...this.state.items, {value:res.loadOrder.displayId, display: `#${res.loadOrder.displayId} [${res.loadOrder.status.displayStatus}]`}]});
              Vibration.vibrate();
            }
            this.setState({content:null});
          });
        toast('Loading...');
      }
    }
  }
  onCheckInUpdateStatus = () => this.onSubmit(true)
  onCheckIn = () => this.onSubmit(false)
  onSubmit = (updateStatus) => {
    const items = this.state.items;
    if (items.length===0) return toast('Please input order to check in');

    if (updateStatus) {
      Alert.alert(
        `Are you sure you want to check in & update order status?`,
        items.map(item => item.display).join('; '),
        [
          {text: 'Cancel'},
          {text: 'Check In & Update', onPress: () => this.onConfirm(items, updateStatus)},
        ],
        { cancelable: true }
      );
    } else {
      this.onConfirm(items, updateStatus);
    }
  }
  onConfirm = (items, updateStatus) => {
    executor(this.props.storeCheckIn, {orderNumbers:items.map(item=>item.value), updateStatus})
      .then(({res}) => {
        if (res) {
          toast('Check in succeed');
          this.props.navigation.goBack();
        }
      });
    toast('Checking in...');
  }
  onClear = () => {
    this.setState({content:''});
  }
  render() {
    return (
      <ScrollView>
        <View style={{flexDirection:'row'}}>
          <View style={{flex:1}}>
            <SearchBar inputStyle={{height:50}} ref='ordernumber' autoFocus placeholder='Order num' lightTheme keyboardType='numeric'
              value={this.state.content} onChangeText={this.onChangeText}/>
          </View>
          <Button title='Search' backgroundColor='transparent' color={primaryColor} onPress={this.onSearch}/>
          <Button title='Clear' backgroundColor='transparent' color={primaryColor} onPress={this.onClear}/>
        </View>
        <List>
          {this.state.items.map((item, index) => <ListItem key={index} title={item.display}
            rightIcon={{name:'clear'}} onPress={()=>this.setState({items:[...this.state.items.slice(0,index), ...this.state.items.slice(index+1)]})}/>)}
        </List>
        <Button containerViewStyle={styles.button} title='Check In & Update Order Status' backgroundColor={primaryColor} onPress={this.onCheckInUpdateStatus}/>
        <Button containerViewStyle={styles.button} title='Check In Only' backgroundColor='white' color='black' onPress={this.onCheckIn}/>
      </ScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    mutation loadOrder($idOrBag:String!) {
      loadOrder(idOrBag:$idOrBag) {
        id
        displayId
        status {
          displayStatus
        }
      }
    }
  `, {
    name: 'loadOrder',
    props: ({loadOrder}) => {
      return {
        loadOrder: (idOrBag) => loadOrder({variables:{idOrBag}})
      };
    }
  }),
  graphql(gql`
    mutation storeCheckIn($storeId:String!,$orderNumbers:[Int]!,$updateStatus:Boolean) {
      storeCheckIn(storeId:$storeId,orderNumbers:$orderNumbers,updateStatus:$updateStatus) {
        id
      }
    }
  `, {
    name: 'storeCheckIn',
    props: ({ownProps:{navigation:{state:{params:{storeId}}}}, storeCheckIn}) => {
      return {
        storeCheckIn: (variables) => storeCheckIn({
          variables:{storeId,...variables},
          refetchQueries: [{
            query: StoragePageQuery,
            variables: { storeId },
          }],
        })
      };
    }
  })
)(StoreCheckInPage);

